package com.customization.huangwm.cronJob.executeActions.lims;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import com.customization.huangwm.utils.LogTool;
import org.apache.axis.components.logger.LogFactory;
import org.apache.commons.logging.Log;

import com.alibaba.fastjson.JSONObject;
import com.customization.huangwm.cronJob.AbstractCronJob;
import com.customization.huangwm.utils.HttpRequest;

import weaver.conn.RecordSet;
import weaver.general.BaseBean;

public class GetInstruments extends AbstractCronJob {

    private LogTool log = new LogTool("/log/huangwm/cronJob/GetInstruments", false);
    private HttpRequest http = new HttpRequest();

    @Override
    public void start() throws Exception {

        int formmodeid = 59161;//formmodeid 测试系统为59161
        int modedatacreater = 1;
        int modedatacreatertype = 0;
        String modedatacreatedate = getCurrentDate();
        String modedatacreatetime = getCurrentTime();
        List<String> outkeys = getOutkey();
        RecordSet rs1 = new RecordSet();
        String sql1 = "insert into uf_SamplingISM(formmodeid,modedatacreater,modedatacreatertype,modedatacreatedate,modedatacreatetime,MODEUUID,outkey,code,name,showname) values(?,?,?,?,?,?,?,?,?,?)";
        int isCounts = 0;
        RecordSet rs2 = new RecordSet();
        String sql2 = "update uf_SamplingISM set code=?,name=?,showname=? where outkey=?";
        int upCounts = 0;
        BaseBean baseBean = new BaseBean();
        String token = baseBean.getPropValue("LIMS", "eop_reqToken").isEmpty() ? "EapLims20200708D1207F4TEST" : baseBean.getPropValue("LIMS", "eop_reqToken");
        String url = baseBean.getPropValue("LIMS", "eop_reqUrl").isEmpty() ? "https://testeop.macaowater.com" : baseBean.getPropValue("LIMS", "eop_reqUrl");
        log.writeLog("token="+token);
        log.writeLog("url="+url);
        if(token.isEmpty() || url.isEmpty()){
            throw new RuntimeException("配置文件token或url为空");
        }
        //GET Instruments
        JSONObject params = new JSONObject();
        params.put("reqNb", http.getTimestamp());
        params.put("reqLang", "zh");
        params.put("reqToken", token);
        JSONObject reqData = new JSONObject();
        reqData.put("plantCode", "01");
        reqData.put("action", "getInstrument");
        params.put("reqData", reqData);

        JSONObject json = http.CallApiPost(url+"/eop/eapToLims/eapapi", JSONObject.toJSONString(params));
        if(json==null){
            throw new RuntimeException("获取接口数据为空");
        }
        JSONObject result = (JSONObject) json.get("result");
        List<JSONObject> instruments = (List<JSONObject>) result.get("instrument");

        for (int i = 0; i < instruments.size(); i++) {
            JSONObject info = instruments.get(i);
            String outkey = info.getString("id");
            String code = info.getString("code");
            String name = info.getString("name");
            String showname = name + "(" + code + ")";

            Object[] insertParams = {
                    formmodeid, modedatacreater, modedatacreatertype, modedatacreatedate, modedatacreatetime, getUUID(),
                    outkey, code, name, showname
            };

            Object[] updateParams = {
                    code, name, showname, outkey
            };

            if (outkeys.size() > 0) {
                //update前先判断是否存在outkey
                if (!outkeys.contains(outkey)) {
                    //insert
                    rs1.executeUpdate(sql1, insertParams);
                    isCounts++;
                } else {
                    rs2.executeUpdate(sql2, updateParams);
                    upCounts++;
                }
            } else {
                //insert
                rs1.executeUpdate(sql1, insertParams);
                isCounts++;
            }
        }

        log.writeLog("数据库表uf_SamplingISM中已存在" + outkeys.size() + "条,本次获取" + instruments.size() + "条," + "插入" + isCounts + "条,更新" + upCounts + "条");

//		RecordSet rs = new RecordSet();
//		String sql = "insert into uf_SamplingISM(outkey,code,name,showname) values(?,?,?,?)";
//		boolean flag = rs.executeBatchSql(sql, insertValues);

    }

    public List<String> getOutkey() {
        List<String> outkeys = new ArrayList<>();
        RecordSet rs = new RecordSet();
        rs.execute("select outkey from uf_SamplingISM");
        while (rs.next()) {
            if (!outkeys.contains(rs.getString("outkey"))) {
                outkeys.add(rs.getString("outkey"));
            }
        }
        return outkeys;
    }

    /**
     * 生成UUID
     *
     * @return
     */
    public String getUUID() {
        String uuid = UUID.randomUUID().toString().toLowerCase();
        return uuid;
    }

    /**
     * 获取当前日期
     *
     * @return yyyy-MM-dd
     */
    public String getCurrentDate() {
        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        return sdf.format(date);
    }

    /**
     * 获取当前时间
     *
     * @return HH:mm:ss
     */
    public String getCurrentTime() {
        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
        return sdf.format(date);
    }

    /**
     * 获取当前日期时间
     *
     * @return yyyy-MM-dd HH:mm:ss
     */
    public String getCurrentTimes() {
        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return sdf.format(date);
    }

    /**
     * 获取当前日期时间
     *
     * @return yyyy-MM-dd HH:mm
     */
    public String getCurrentTimes2() {
        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        return sdf.format(date);
    }
}
